package action;

import org.json.JSONObject;

import bean.User;
import service.UserService;
import utils.AjaxResult;
import utils.HttpsRequest;

public class TestAction extends BaseAction {
 
    private static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    
    private String accessToken = "";
    
    private UserService userService;
    private WechatAccessTokenApi wechatAccessTokenApi;
    
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    
    public void setWechatAccessTokenApi(WechatAccessTokenApi wechatAccessTokenApi) {
        this.wechatAccessTokenApi = wechatAccessTokenApi;
    }
    
    public void updateUserInfoByOpenId(){
        //初始化要更新的user_id范围
        int start = 788;
        int end = 788;
        String tableName = "user";
        String[] keys = { "nickname", "headimgurl", "openid" };
        User user = null;
        String openId = null;
        String userInfoText = null;
        StringBuilder builder = null;
        for(int i=start;i<=end;i++){
            System.out.println("id = "+i);
            user = userService.getByUserId(i);
            openId = user.getOpenId();
            System.out.println("openId = "+openId);
            // 构造请求参数
            accessToken = wechatAccessTokenApi.getAccessToken();
            System.out.println("accessToken = "+accessToken);
            builder = new StringBuilder();
            builder.append("access_token=").append(accessToken.trim()).append("&")
                    .append("openid=").append(openId).append("&")
                    .append("lang=zh_CN");
            // 发起https请求
            try {
                userInfoText = HttpsRequest.sendGet(GET_USER_INFO_URL, builder.toString());
                System.out.println("userInfoText = "+userInfoText);
            } catch (Exception e) {
                e.printStackTrace();
                userInfoText = null;
            }
            // 处理请求返回的结果
            JSONObject userInfoResponse = userInfoText == null ? null : new JSONObject(userInfoText);
            if (userInfoResponse != null && userInfoResponse.has("openid")) {
                // 获取成功
                System.out.println("userInfo = "+userInfoResponse.toString());
                // 更新到数据库
                userService.updateUserInfoByOpenId(openId, userInfoResponse.getString("nickname"), userInfoResponse.getString("headimgurl"));
                
               
                
            } else {
                // 获取失败
                System.out.println("获取失败 ");
            }
        }
        
       
    }
}
